var Activity,
	view,
	viewClass,
	BitmapFactory,
	StringBuffer,
	Byte,
	CompressFormat,
	ByteArrayOutputStream,
	str,
	bBitmap,
	bStream,
	bytes,
	Base64;
var bitmap = null;

function plusReady() {
    //显示消费信息
    var id = getUrlParam("id");
    var user = userLogin();

    PaintPage(id, user);

    // 绑定方法
    BindEvent(id);
}
if (window.plus) {
    plusReady();
} else {
    document.addEventListener('plusready', plusReady, false);
}

function PaintPage(id, user) {
	
	//不是商家可扫订单码
	if( -1 == ( [2,3].indexOf(user.user_type) ) ){
		plus.nativeUI.alert("您不是商家不可扫码！"); back(); return;
	}
	
    $.ajax({
        type: "POST",
        url: configManager.RequstUrl + "/api/order/info",
        async: true,
        data: { "userid": user.id, "token": user.token, "orderid": id }
    }).done(function (data) {
        if ("success" == data.state) {
            var order = data.data;
        	if (order.seller.code != user.code) { 
        		plus.nativeUI.alert("不是本店订单，不允许操作！"); back(); return; 
        	}
            //确认消费
            if( ( 0 == order.payment && 0 == order.status ) || ( 0 < order.payment && 1 == order.status ) ){
		        var postdata = { "userid": user.id, "token": user.token, "order": order.id };
		        $.ajax({
		            type: "POST",
		            url: configManager.RequstUrl + "api/store/orderdone",
		            async: true,
		            data: postdata
		        }).done(function (data) {
		            if ("success" == data.state) {
		                plus.ui.alert(data.message, function () {
		                   plus.webview.currentWebview().close();
		                }, configManager.alerttip, configManager.alertCtip);
		            } else {
		                plus.ui.alert(data.message, function () { }, configManager.alerttip, configManager.alertCtip);
		            }
		        });            	
            }

            var html = [];
            //订单图片
            html.push("<div class='item-02-wrap t-c'><img src='' id='orderbarcode' width='168' height='168' /><p class='mt10'>订单号码："+ order.order_sn +"&nbsp; &nbsp;&nbsp;&nbsp;订单金额:"+ order.money +"</p></div>");
            
            //订单状态
            var moneytips = "本单未付金额:" + order.money;
            var classname = 'off-org-block';
            if( ( 0 == order.payment ) && ( 1 < order.status )  ){
        		moneytips = "您已经支付金额";
        		classname = 'off-green-block';
            }
            else if( 0 < order.status ){
                moneytips = "您已经支付金额";
                classname = 'off-green-block';
            }
            
            html.push("<div class='item-02-wrap t-c'><span class='"+ classname +"'>"+ moneytips +"</span></div>");
            
            
            //订单商品
            html.push('<div class="table-list-wrap"><table><tbody><tr> <th width="50%">项目名称</th><th>数量</th><th>单价</th></tr>');
            $.each(order.goods, function(i, goods) {
            	html.push('<tr><td>'+ goods.goods_title +'</td><td>'+ goods.quantity +'</td><td>'+ goods.goods_price +'</td></tr>')
            });
            html.push('</tbody></table></div>');

            $("#content").html(html.join(""));

            $.ajax({
                type: 'Get',
                url: configManager.RequstUrl + 'api/common/qrcode?type=order&order=' + order.id
            }).done(function (data) {
                if (data.state != "success") {
                    console.log(data.message);
                    return;
                }
                $("#orderbarcode").attr("src", data.uri);
            });


        }
        else {
            plus.ui.alert(data.message, function () { }, configManager.alerttip, configManager.alertCtip);
        }
    });
    
    //

}

function BindEvent(id) {
	// 导入Native.js需要的原生对象
	Activity = plus.android.runtimeMainActivity();
	BitmapFactory = plus.android.importClass("android.graphics.BitmapFactory");
	StringBuffer = plus.android.importClass("java.lang.StringBuffer");
	Byte = plus.android.importClass("java.lang.Byte");
	CompressFormat = plus.android.importClass("android.graphics.Bitmap.CompressFormat");
	bBitmap = plus.android.importClass("android.graphics.Bitmap");
	ByteArrayOutputStream = plus.android.importClass("java.io.ByteArrayOutputStream");
	Base64 = plus.android.importClass("android.util.Base64");
	
    // 保存到相册
	mui.init({ gestureConfig:{ "longtap": true } });	//定义长按屏幕
	document.getElementById('body').addEventListener("longtap",function(){
	     
	     saveGallery(id);
	     
	});

    // 回退
    $("#back").on("click", function () {
        var mainview = plus.webview.getWebviewById(pageName.main);
        mainview.evalJS("gohome()");
    });

}

//长按屏幕保存到相册
function saveGallery(id) {
//  var dtask = plus.downloader.createDownload(url, {}, function (d, status) {
//      // 下载完成
//      if (status == 200) {
//          console.log(d.filename);
//          var filepath = plus.io.convertLocalFileSystemURL(d.filename);
//          console.log(filepath);
//          // 保存相册
//          plus.gallery.save(filepath);
//          plus.nativeUI.alert("保存成功");
//          // 删除
//          plus.io.resolveLocalFileSystemURL(filepath, function (entry) {
//              entry.remove(function (e) { }, function (e) { });
//          }, function (e) { });
//
//      } else {
//          plus.nativeUI.alert("Download failed: " + status);
//      }
//  });
//  //dtask.addEventListener( "statechanged", onStateChanged, false );
//  dtask.start();

	view = Activity.getCurrentFocus();
	plus.android.invoke(view,"setDrawingCacheEnabled",true);
	plus.android.invoke(view,"buildDrawingCache");
    //对view截图，存入bitmap中
    bitmap = plus.android.invoke(view,"getDrawingCache");
    if(null != bitmap){
    	console.log("截图成功");
    	try{
    		str = new StringBuffer();
    		bStream = new ByteArrayOutputStream();
    		bitmap.compress(bBitmap.CompressFormat.PNG, 100, bStream);
    		bStream.flush();
    		bStream.close();
    		bytes = bStream.toByteArray();
    		str.append(Base64.encodeToString(bytes, Base64.NO_WRAP));
    	} catch(e){
    		console.log(e.message);
    	}
    	var imgFile = "data:image/png;base64," + str.toString();
    	var filename = "order_" + id.toString() + ".png";
    	
    	
    	
		plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, function(fs) {
			fs.root.getFile('test.png', {create: true}, 
			function(fileEntry) {
				console.log(fileEntry.fullPath);
				fileEntry.createWriter(function(writer) {
				writer.onwrite = function(e) {
					console.log("Write data success!");
				};
				writer.write( imgFile );
				});
				},function(e){
					console.log("getFile failed: " + e.message);
				});
				}, function(e) {
					console.log("Request file system failed: " + e.message);
			});
		
		
    	
    	
//  	console.log(imgFile); 
//  	$("#orderbarcode").attr("src", "data:image/png;base64," + str.toString());
    	
    	
    }

}